package com.moli.iov.base.remote.impl;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.moli.iov.base.cache.mongodb.TerminalInstallLogsService;
import com.moli.iov.base.enums.AuditResultsEnum;
import com.moli.iov.base.enums.AuditStatusEnum;
import com.moli.iov.base.enums.AuthorizedSourceEnum;
import com.moli.iov.base.model.TerminalInstallationAuditParam;
import com.moli.iov.base.model.dto.req.QueryTerminalInstallationAuditListParamDto;
import com.moli.iov.base.model.dto.req.TerminalInstallLogsReqDto;
import com.moli.iov.base.model.dto.req.TerminalInstallationAuditReqDto;
import com.moli.iov.base.model.dto.res.TerminalInstallationAuditResDto;
import com.moli.iov.base.model.mongo.TerminalInstallLogs;
import com.moli.iov.base.model.po.TerminalInstallationAudit;
import com.moli.iov.base.model.po.VehicleTbox;
import com.moli.iov.base.remote.ITerminalInstallationAuditRemoteService;
import com.moli.iov.base.service.ITerminalInstallationAuditService;
import com.moli.iov.base.service.IVehicleTboxService;
import com.moli.iov.base.util.CollectionUtils;
import com.moli.iov.enums.UserTypeEnum;
import com.moli.iov.model.dto.req.PageExtend;
import com.moli.iov.rest.RestResponse;
import com.moli.iov.util.CommonUtils;
import com.moli.iov.util.JsonUtils;
import com.moli.iov.util.SnowflakeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 设备管理> 终端安装管理 审核
 *
 * @author wanghualin
 * @date 2020 -02-24 12:54:30
 */
@Slf4j
@Service(group = "${service.group}")
@Transactional(rollbackFor = Exception.class)
public class TerminalInstallationAuditRemoteServiceImpl implements ITerminalInstallationAuditRemoteService {
    @Autowired
    private ITerminalInstallationAuditService iTerminalInstallationAuditService;

    @Autowired
    private IVehicleTboxService iVehicleTboxService;
    @Autowired
    private TerminalInstallLogsService logsService;

    /**
     * 设备管理> 终端安装管理-安装确认列表
     *
     * @param dto
     * @return
     */
    @Override
    public RestResponse<PageExtend<TerminalInstallationAuditResDto>> listTerminalInstallationAudit(QueryTerminalInstallationAuditListParamDto dto) {
        log.info("设备管理>-终端安装管理-确认安装列表-入参:{}",dto);
        List<TerminalInstallationAuditResDto> list = new ArrayList<>();
        TerminalInstallationAuditParam param = new TerminalInstallationAuditParam();
        if (UserTypeEnum.COMPANY.getFlag() == dto.getSysUserType().intValue()) {
            param.queryEqCompanyId(dto.getSysCompanyId());
        } else {
            param.queryEqCompanyId(dto.getCompanyId());
        }
        param.queryBetweenRegisterTime(dto.getStartTime(), dto.getEndTime());
        param.queryEqDeviceId(dto.getDeviceId());
        param.queryEqVin(dto.getVin());
        param.queryEqAuditStatus(AuditStatusEnum.NO.getCode());
        IPage<TerminalInstallationAudit> page = new Page(dto.getPageNum(), dto.getPageSize());
        IPage<TerminalInstallationAudit> auditPage = iTerminalInstallationAuditService.page(page, param.get());
        PageExtend<TerminalInstallationAuditResDto> res = new PageExtend<>();
        if (auditPage!=null && !CollectionUtils.isEmpty(auditPage.getRecords())) {
            List<TerminalInstallationAudit> auditList = auditPage.getRecords();
            for (TerminalInstallationAudit record : auditList) {
                TerminalInstallationAuditResDto audit = new TerminalInstallationAuditResDto();
                CommonUtils.copyProperties(record, audit);
                list.add(audit);
            }
            res.setRecords(list);
        }
        res.setPageSize(dto.getPageSize());
        res.setTotal((long) list.size());
        res.setPageNumber(dto.getPageNum());
        return RestResponse.success(res);
    }

    @Override
    public RestResponse audit(TerminalInstallationAuditReqDto dto) {
        log.info("设备管理>-终端安装管理-确认安装-安装审核入参:{}",dto);
        TerminalInstallationAudit audit = iTerminalInstallationAuditService.getById(dto.getId());
        Date now = Calendar.getInstance().getTime();
        if (audit == null) {
            return RestResponse.failure("安装记录不存在");
        }
        //如果是企业用户
        if (UserTypeEnum.COMPANY.getFlag() == dto.getSysUserType().intValue()) {
            if (dto.getSysCompanyId().longValue() != audit.getCompanyId().longValue()) {
                return RestResponse.failure("没有操作权限");
            }
        }
        if (audit.getAuditStatus().intValue() == AuditStatusEnum.YES.getCode()) {
            return RestResponse.failure("不能重复审核");
        }
        //不同意安装
        if (dto.getAuditResults().intValue() == AuditResultsEnum.NO.getCode()) {
            audit.setModifiedUser(dto.getSysUserId().toString());
            audit.setGmtModified(now);
            audit.setAuditStatus(AuditStatusEnum.YES.getCode());
            boolean b = iTerminalInstallationAuditService.saveOrUpdate(audit);
            if (!b) {
                return RestResponse.failure("操作更新失败！");
            }
        } else {
            //同意安装
            //校验数据//TODO
            //是否已绑定
            VehicleTbox binding= iVehicleTboxService.getVehicleTboxByVin(audit.getVin());
            VehicleTbox oldVehicleTbox = iVehicleTboxService.getVehicleTboxByDeviceId(audit.getDeviceId());
            if (binding!=null){
                return  RestResponse.failure("终端安装失败！车架号已存在绑定关系");
            }
            if (oldVehicleTbox==null){
                return  RestResponse.failure("终端安装失败！终端不存在");
            }
            if(StringUtils.isNotBlank(oldVehicleTbox.getVin())){
                return  RestResponse.failure("终端安装失败！终端已存在绑定关系");
            }

            VehicleTbox newTbox=new VehicleTbox();
            CommonUtils.copyProperties(oldVehicleTbox,newTbox);
            Date date=Calendar.getInstance().getTime();
            newTbox.setVin(audit.getVin());
            newTbox.setRegisterTime(date);
            newTbox.setGmtModified(date);
            newTbox.setModifiedUser(dto.getSysUserId().toString());
            newTbox.setModifiedRealName(dto.getSysRealName());
            boolean b = iVehicleTboxService.updateVehicleTbox(oldVehicleTbox, newTbox);
            if(!b){
                return RestResponse.failure("操作更新失败！");
            }
            audit.setModifiedUser(dto.getSysUserId().toString());
            audit.setGmtModified(now);
            audit.setAuditStatus(AuditStatusEnum.YES.getCode());
            boolean c = iTerminalInstallationAuditService.saveOrUpdate(audit);
            if(!c){
                return RestResponse.failure("操作更新失败！");
            }
        }
        //添加安装记录
        saveTerminalInstallLogs(audit, dto);
        return RestResponse.success();
    }
    /**
     * 安装日志记录
     * @param dto
     * @return
     */
    @Override
    public RestResponse<PageExtend<TerminalInstallLogs>>   listTerminalInstallLogs(TerminalInstallLogsReqDto dto) {
        log.info("设备管理>-终端安装管理-安装记录列表-入参:{}",dto);
        return logsService.listTerminalInstallLogs(dto);
    }

    /**
     * 添加安装日志
     *
     * @param audit
     * @param dto
     */
    public void saveTerminalInstallLogs(TerminalInstallationAudit audit, TerminalInstallationAuditReqDto dto) {
        Date date = Calendar.getInstance().getTime();
        TerminalInstallLogs logs = new TerminalInstallLogs();
        logs.setAuthorizedResult(dto.getAuditResults());
        logs.setAuthorizedResultStr(AuditResultsEnum.getCodeName(dto.getAuditResults()));
        logs.setAuthorizedSource(AuthorizedSourceEnum.REGISTERED.getCode());
        logs.setAuthorizedSourceStr(AuthorizedSourceEnum.REGISTERED.getName());
        logs.setVin(audit.getVin());
        logs.setDeviceId(audit.getDeviceId());
        logs.setDeviceModel(audit.getDeviceModel());
        logs.setCompanyId(audit.getCompanyId());
        logs.setCompanyName(audit.getCompanyName());
        logs.setCreateUserId(dto.getSysUserId());
        logs.setCreateRealName(dto.getSysRealName());
        logs.setSerialNumber(SnowflakeUtils.getId());
        logs.setIccid(audit.getIccid());
        logs.setGmtCreate(date);
        logsService.saveTerminalInstallLogs(logs);
    }




}
